﻿using System.Linq;
using System.Web.Mvc;
using DreamStore.WebShop.Extensibility;
using DreamStore.WebShop.Models;
using DreamStore.WebShop.Services;
using Orchard;
using Orchard.ContentManagement;
using Orchard.Core.Title.Models;

namespace DreamStore.WebShop.Controllers
{
    public class PayPalController : Controller
    {
        private readonly IPayPalService _payPalService;
        private readonly IOrderService _orderService;

        public PayPalController(IPayPalService payPalService, IOrderService orderService)
        {
            _payPalService = payPalService;
            _orderService = orderService;
        }

        public ActionResult RedirectToPayPal(string orderReference)
        {
            var order = _orderService.GetOrderByNumber(orderReference);
            var orderLines = (from detailRecord in order.Details
                              let product = _orderService.GetProduct(detailRecord.ProductId)
                              let title = product.As<TitlePart>().Title
                              select new OrderLine
                              {
                                  ProductName = title,
                                  Quantity = detailRecord.Quantity,
                                  UnitPrice = detailRecord.UnitPrice,
                                  TotalPrice = detailRecord.SubTotal
                              });
            var payPalRedirect = _payPalService.ExpressCheckout(orderLines);
            Session["token"] = payPalRedirect.Token;
            Session["order"] = order.Number;
            return Redirect(payPalRedirect.Url);
        }

        public ActionResult ReturnFromPayPal(string token)
        {
            var order = Session["order"];
            var tokenFromSession = Session["token"];
            var tokenFromPayPal = token;
            if (tokenFromSession != null && tokenFromSession.ToString() == tokenFromPayPal)
            {
                return RedirectToAction("PaymentResponse", "Order", new { area = "DreamStore.WebShop", paymentId = "[PayPalIdForReals...]", result = "PayPalOk", orderReference = order });
            }
            return RedirectToAction("Index", "ShoppingCart", new { area = "DreamStore.WebShop" });
        }

        public ActionResult CancelFromPayPal()
        {
            return RedirectToAction("Summary", "Checkout", new { area = "DreamStore.WebShop" });
        }
    }

}